#!/bin/sh

if [[ "$EUID" -ne 0 ]]; then
	echo "Must be executed by root"
	exit 1
fi
shutdown_mode=$(basename "$1")  ## CAPTURE "poweroff" or "reboot"
echo "Killing non-tty daemontools-encore services..."
for serv in /etc/rc/*; do
  servname=$(basename "$serv")

  if [[ ! "$servname" =~ ^tty|^dtinit ]]; then
    lk_killsvc "$serv" 0
    echo "[ !! ] Terminated $servname"
  fi
done
echo;
echo "[ {} ] Unmounting /dev/pts and /dev/shm..."
umount /dev/pts
umount /dev/shm
echo;
interfaces=$(ip link show | awk -F': ' '{print $2}')
for interface in $interfaces; do
  ip link set dev "$interface" down
  echo "[ <> ] Interface $interface is down"
done
echo;
echo "[ !! ] pkill -15 (requesting)..."
pkill -15 -e 1
echo "[ !! ] pkill -9 (murdering)..."
pkill -9 -e 1
echo;
echo "[ {} ] swapoff -a..."
swapoff -a
echo "[ {} ] Remounting filesystems as read-only..."
echo "u" > /proc/sysrq-trigger
sleep 3
echo "[ {} ] Syncing filesystems..."
sync
echo "s" > /proc/sysrq-trigger
sleep 3
echo;
if test "$shutdown_mode" = "reboot"; then
  echo "[ OK ] Rebooting..."
  sleep 1
  echo "b" > /proc/sysrq-trigger
else
  echo "[ OK ] Powering off..."
  sleep 1
  echo "o" > /proc/sysrq-trigger
fi
